<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import * as echarts from 'echarts';
import { HouseIcon, UserIcon, ShopIcon, LocationIcon, VanIcon, VisitorIcon, RenterIcon } from '@/components/icons';
import {
  getHeadInfo,
  getDashboardStats,
  getHouseStatistics,
  getPaymentStatistics,
  getRecentNotices,
  getPendingWorkOrders,
  type HeadInfo,
  type DashboardStats,
  type HouseStatistics,
  type PaymentStatistics,
  type Notice,
  type PendingWorkOrder
} from '@/api/dashboard';

defineOptions({
  name: "Welcome"
});

// 响应式数据
const loading = ref(true);
const headInfo = ref<HeadInfo>({
  name: '',
  contact: '',
  phone: '',
  createTime: '',
  cellCount: 0
});

const dashboardStats = ref<DashboardStats>({
  houseCount: 0,
  ownerCount: 0,
  renterCount: 0,
  visitorCount: 0,
  parkingSpaceCount: 0,
  vehicleCount: 0,
  vendorCount: 0
});

const houseStats = ref<HouseStatistics>({
  totalHouses: 0,
  occupiedHouses: 0,
  rentedHouses: 0,
  vacantHouses: 0
});

const paymentStats = ref<PaymentStatistics>({
  totalRepairPrice: 0,
  totalAdvertPrice: 0,
  unpaidPrice: 0,
  totalDeposit: 0
});

const recentNotices = ref<Notice[]>([]);
const pendingWorkOrders = ref<PendingWorkOrder[]>([]);

// 计算属性
const occupancyRate = computed(() => {
  if (houseStats.value.totalHouses === 0) return 0;
  return Math.round((houseStats.value.occupiedHouses / houseStats.value.totalHouses) * 100);
});

const rentalRate = computed(() => {
  if (houseStats.value.totalHouses === 0) return 0;
  return Math.round((houseStats.value.rentedHouses / houseStats.value.totalHouses) * 100);
});

const vacancyRate = computed(() => {
  if (houseStats.value.totalHouses === 0) return 0;
  return Math.round((houseStats.value.vacantHouses / houseStats.value.totalHouses) * 100);
});

// 图表引用
const paymentChartRef = ref<HTMLElement>();

// 初始化临时数据
const initMockData = () => {
  // 头部信息
  headInfo.value = {
    name: '国信安',
    contact: '张三',
    phone: '17898458479',
    createTime: '2025-09-28 16:54:01',
    cellCount: 2
  };

  // 核心统计数据
  dashboardStats.value = {
    houseCount: 288,
    ownerCount: 7,
    renterCount: 1,
    visitorCount: 8,
    parkingSpaceCount: 5,
    vehicleCount: 3,
    vendorCount: 1
  };

  // 房屋统计数据
  houseStats.value = {
    totalHouses: 288,
    occupiedHouses: 12,
    rentedHouses: 1,
    vacantHouses: 275
  };

  // 费用统计数据
  paymentStats.value = {
    totalRepairPrice: 451,
    totalAdvertPrice: 0,
    unpaidPrice: 861,
    totalDeposit: 21532.9
  };

  // 通知公告数据
  recentNotices.value = [
    {
      id: 1,
      tenantId: 1,
      noticeName: '测试公告',
      noticeType: '紧急',
      cellId: 1,
      status: '已发布',
      publisher: '测试用户',
      content: '测试内容',
      isTop: 0,
      createTime: '2025-09-28 15:24:02',
      updateTime: '2025-10-13 19:10:31',
      isDeleted: 0
    }
  ];

  // 待办工单数据
  pendingWorkOrders.value = [
    {
      details: '123',
      createTime: '2025-10-14 17:50:35',
      importance: '一般',
      contactPhone: '19956666666',
      contactPerson: '3123',
      cellName: '周森国际',
      roomNumber: '1'
    }
  ];

};

// 初始化数据
const initData = async () => {
  try {
    loading.value = true;

    // 并行加载所有数据
    const [
      headData,
      statsData,
      houseData,
      paymentData,
      noticesData,
      workOrdersData
    ] = await Promise.all([
      getHeadInfo(),
      getDashboardStats(),
      getHouseStatistics(),
      getPaymentStatistics(),
      getRecentNotices(),
      getPendingWorkOrders()
    ]);

    // 设置数据
    if (headData.code === 0) {
      headInfo.value = headData.data;
    }

    if (statsData.code === 0) {
      dashboardStats.value = statsData.data;
    }

    if (houseData.code === 0) {
      houseStats.value = houseData.data;
    }

    if (paymentData.code === 0) {
      paymentStats.value = paymentData.data;
    }

    if (noticesData.code === 0) {
      recentNotices.value = noticesData.data;
    }

    if (workOrdersData.code === 0) {
      pendingWorkOrders.value = workOrdersData.data;
    }


    // 初始化图表
    setTimeout(() => {
      initPaymentChart();
    }, 100);

  } catch (error) {
    console.error('加载数据失败:', error);
    // 如果接口失败，使用临时数据
    initMockData();
  } finally {
    loading.value = false;
  }
};

// 缴费统计柱状图
const initPaymentChart = () => {
  if (!paymentChartRef.value) return;

  const chart = echarts.init(paymentChartRef.value);

  const updateChart = () => {
    const option = {
    title: {
      text: '缴费统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params: any) {
        const data = params[0];
        const value = data.value;
        const formattedValue = value >= 10000 ? (value / 10000).toFixed(1) + '万元' : value + '元';
        return `${data.name}<br/>${data.seriesName}: ${formattedValue}`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['总维修价格', '总广告费', '未缴费用', '预存总金额'],
      axisLabel: {
        interval: 0,
        rotate: 0,
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      name: '金额(元)',
      nameTextStyle: {
        fontSize: 12
      },
      axisLabel: {
        formatter: function(value: number) {
          if (value >= 10000) {
            return (value / 10000).toFixed(1) + '万';
          }
          return value;
        }
      }
    },
    series: [{
      name: '金额',
      type: 'bar',
      data: [
        paymentStats.value.totalRepairPrice,
        paymentStats.value.totalAdvertPrice,
        paymentStats.value.unpaidPrice,
        paymentStats.value.totalDeposit
      ],
      itemStyle: {
        color: '#E6A23C',
        borderRadius: [4, 4, 0, 0]
      },
      label: {
        show: true,
        position: 'top',
        formatter: function(params: any) {
          const value = params.value;
          if (value >= 10000) {
            return (value / 10000).toFixed(1) + '万';
          }
          return value;
        },
        fontSize: 12,
        color: '#333'
      },
      barWidth: '60%'
    }]
    };
    chart.setOption(option);
  };

  // 初始更新图表
  updateChart();

  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize();
  });

  // 返回更新函数，供外部调用
  return updateChart;
};


// 监听缴费统计数据变化，自动更新图表
watch(paymentStats, () => {
  if (paymentChartRef.value) {
    setTimeout(() => {
      initPaymentChart();
    }, 100);
  }
}, { deep: true });

onMounted(() => {
  initData();
});
</script>

<template>
  <div class="dashboard-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-loading
        element-loading-text="正在加载数据..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        style="width: 100%; height: 100vh;"
      />
    </div>
    <!-- 顶部信息栏 -->
    <div class="header-section">
      <div class="header-left">
        <h1 class="company-name">{{ headInfo.name }}</h1>
        <div class="community-info">联系人：{{ headInfo.contact }} | 电话：{{ headInfo.phone }}</div>
      </div>
      <div class="header-center">
        <div class="welcome-banner">欢迎使用智慧物业系统,开启你的智慧生活。</div>
      </div>
      <div class="header-right">
        <div class="info-item">
          <span class="label">小区数量 (个)</span>
          <span class="value">{{ headInfo.cellCount }}</span>
        </div>
        <div class="info-item">
          <span class="label">注册时间</span>
          <span class="value">{{ headInfo.createTime.split(' ')[0] }}</span>
        </div>
      </div>
    </div>

    <!-- 核心统计指标区 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon house-icon">
            <HouseIcon />
          </div>
          <div class="stat-number">{{ dashboardStats.houseCount }}</div>
          <div class="stat-label">房屋认证数</div>
        </div>
        <div class="stat-card">
          <div class="stat-icon owner-icon">
            <UserIcon />
          </div>
          <div class="stat-number">{{ dashboardStats.ownerCount }}</div>
          <div class="stat-label">业主数</div>
        </div>
        <div class="stat-card">
          <div class="stat-icon tenant-icon">
            <RenterIcon />
          </div>
          <div class="stat-number">{{ dashboardStats.renterCount }}</div>
          <div class="stat-label">租客数</div>
        </div>
        <div class="stat-card">
          <div class="stat-icon visitor-icon">
            <VisitorIcon />
          </div>
          <div class="stat-number">{{ dashboardStats.visitorCount }}</div>
          <div class="stat-label">访客数</div>
        </div>
        <div class="stat-card">
          <div class="stat-icon vendor-icon">
            <ShopIcon />
          </div>
          <div class="stat-number">{{ dashboardStats.vendorCount }}</div>
          <div class="stat-label">供应商数</div>
        </div>
        <div class="stat-card">
          <div class="stat-icon parking-icon">
            <LocationIcon />
          </div>
          <div class="stat-number">{{ dashboardStats.parkingSpaceCount }}</div>
          <div class="stat-label">车位数</div>
        </div>
        <div class="stat-card">
          <div class="stat-icon vehicle-icon">
            <VanIcon />
          </div>
          <div class="stat-number">{{ dashboardStats.vehicleCount }}</div>
          <div class="stat-label">登记车辆数</div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- 左侧列 -->
        <el-col :span="12">
          <!-- 房屋统计 -->
          <el-card class="module-card" shadow="hover">
            <template #header>
              <div class="card-header">房屋统计</div>
            </template>
            <div class="housing-stats">
              <div class="progress-item">
                <div class="progress-label">入住率</div>
                <div class="progress-bar">
                  <div class="progress-fill" :style="{ width: occupancyRate + '%' }"></div>
                </div>
                <div class="progress-value">{{ occupancyRate }}%</div>
              </div>
              <div class="progress-item">
                <div class="progress-label">出租率</div>
                <div class="progress-bar">
                  <div class="progress-fill rental" :style="{ width: rentalRate + '%' }"></div>
                </div>
                <div class="progress-value">{{ rentalRate }}%</div>
              </div>
              <div class="progress-item">
                <div class="progress-label">空置率</div>
                <div class="progress-bar">
                  <div class="progress-fill vacant" :style="{ width: vacancyRate + '%' }"></div>
                </div>
                <div class="progress-value">{{ vacancyRate }}%</div>
              </div>
            </div>
          </el-card>

          <!-- 满意度（暂时隐藏，后续可能需要） -->
          <!-- <el-card class="module-card" shadow="hover">
            <template #header>
              <div class="card-header">满意度</div>
            </template>
            <div ref="satisfactionChartRef" class="chart-container"></div>
          </el-card> -->

          <!-- 待办工单 -->
          <el-card class="module-card" shadow="hover">
            <template #header>
              <div class="card-header">待办工单</div>
            </template>
            <div class="work-order-list">
              <div
                v-for="(order, index) in pendingWorkOrders"
                :key="index"
                class="work-order-item"
              >
                <div class="order-title">{{ order.details }}</div>
                <div class="order-info">
                  <span class="order-cell">{{ order.cellName }}</span>
                  <span class="order-room">{{ order.roomNumber }}室</span>
                </div>
                <div class="order-time">{{ order.createTime }}</div>
                <div class="order-contact">联系人：{{ order.contactPerson }} ({{ order.contactPhone }})</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧列 -->
        <el-col :span="12">
          <!-- 缴费统计 -->
          <el-card class="module-card" shadow="hover">
            <template #header>
              <div class="card-header">缴费统计</div>
            </template>
            <div class="payment-stats">
              <div ref="paymentChartRef" class="chart-container"></div>
            </div>
          </el-card>


          <!-- 通知公告 -->
          <el-card class="module-card" shadow="hover">
            <template #header>
              <div class="card-header">通知公告</div>
            </template>
            <div class="notice-list">
              <div
                v-for="notice in recentNotices"
                :key="notice.id"
                class="notice-item"
              >
                <div class="notice-title">{{ notice.noticeName }}</div>
                <div class="notice-time">{{ notice.createTime }}</div>
                <div class="notice-publisher">发布人：{{ notice.publisher }}</div>
              </div>
            </div>
          </el-card>

          <!-- 工单统计（暂时隐藏，后续可能需要） -->
          <!-- <el-card class="module-card" shadow="hover">
            <template #header>
              <div class="card-header">工单统计</div>
            </template>
            <div ref="workOrderChartRef" class="chart-container"></div>
          </el-card> -->

          <!-- 开门类型统计（暂时隐藏，后续可能需要） -->
          <!-- <el-card class="module-card" shadow="hover">
            <template #header>
              <div class="card-header">开门类型统计</div>
            </template>
            <div class="door-opening-stats">
              <div class="total-openings">{{ doorOpeningStats.total_openings }} 总开门次数</div>
              <div ref="doorOpeningChartRef" class="chart-container"></div>
            </div>
          </el-card> -->
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  position: relative;
}

.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
}

/* 顶部信息栏 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left .company-name {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: bold;
}

.community-info {
  color: #666;
  font-size: 14px;
  margin-top: 5px;
}

.welcome-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 10px 20px;
  border-radius: 20px;
  font-size: 16px;
}

.header-right {
  display: flex;
  gap: 20px;
}

.info-item {
  text-align: center;
}

.info-item .label {
  display: block;
  color: #666;
  font-size: 12px;
}

.info-item .value {
  display: block;
  color: #333;
  font-size: 18px;
  font-weight: bold;
}

/* 核心统计指标区 */
.stats-section {
  margin-bottom: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 20px;
  width: 100%;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  transition: transform 0.2s;
  min-height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.stat-icon {
  font-size: 32px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

/* 主内容区 */
.main-content {
  margin-top: 20px;
}

.module-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

/* 房屋统计 */
.housing-stats {
  padding: 10px 0;
}

.progress-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.progress-label {
  width: 60px;
  font-size: 14px;
  color: #666;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  margin: 0 10px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #67C23A;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-fill.rental {
  background-color: #409EFF;
}

.progress-fill.vacant {
  background-color: #E6A23C;
}

.progress-value {
  width: 40px;
  text-align: right;
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

/* 图表容器 */
.chart-container {
  height: 200px;
  width: 100%;
}

/* 缴费统计 */
.payment-stats {
  padding: 10px 0;
}

.payment-stats .chart-container {
  height: 350px;
  width: 100%;
}



/* 通知公告 */
.notice-list {
  max-height: 200px;
  overflow-y: auto;
}

.notice-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.notice-item:last-child {
  border-bottom: none;
}

.notice-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.notice-time {
  font-size: 12px;
  color: #999;
}

.notice-publisher {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

/* 待办工单 */
.work-order-list {
  max-height: 200px;
  overflow-y: auto;
}

.work-order-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.work-order-item:last-child {
  border-bottom: none;
}

.order-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.order-info {
  display: flex;
  gap: 10px;
  margin-bottom: 4px;
}

.order-cell {
  font-size: 12px;
  color: #409EFF;
  background: #f0f9ff;
  padding: 2px 6px;
  border-radius: 4px;
}

.order-room {
  font-size: 12px;
  color: #67C23A;
  background: #f0f9ff;
  padding: 2px 6px;
  border-radius: 4px;
}

.order-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.order-contact {
  font-size: 12px;
  color: #666;
}

/* 开门类型统计 */
.door-opening-stats {
  text-align: center;
}

.total-openings {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .stats-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }

  .stat-card {
    padding: 15px;
    min-height: 100px;
  }

  .stat-icon {
    font-size: 24px;
  }

  .stat-number {
    font-size: 20px;
  }

  .stat-label {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: 1fr;
    gap: 10px;
  }

  .dashboard-container {
    padding: 10px;
  }

  .header-section {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }

  .header-right {
    justify-content: center;
  }
}
</style>
